package com.neusoft.hash;

import com.neusoft.hash.entity.Employee;

import java.util.Objects;

/**
 * @Author lichunlong lcl253137@alibaba-inc.com
 * @Desc 表示HashTable的数组部分
 * @Date 2024-12-28
 */
public class EmployeeHashTable {

    private EmployeeLinkedList[] employeeLinkedListArray;

    /**
     * 表示有多少条链表
     */
    private int employeeLinkedListSize;

    public EmployeeHashTable(int size) {
        this.employeeLinkedListSize = size;
        // 初始化empLinkedListArray
        employeeLinkedListArray = new EmployeeLinkedList[size];

        for (int i = 0; i < size; i++) {
            employeeLinkedListArray[i] = new EmployeeLinkedList();
        }
    }

    //添加雇员
    public void add(Employee employee) {
        // 根据员工的id, 得到该员工应当添加到哪条链表
        int EmployeeLinkedListNo = hashFun(employee.id);
        // 将employee添加到对应的链表中
        employeeLinkedListArray[EmployeeLinkedListNo].add(employee);
    }

    /**
     * 编写散列函数, 使用一个简单取模法
     *
     * @param employeeId employee编号
     * @return 取模后的链表编号
     */
    public int hashFun(int employeeId) {
        return employeeId % employeeLinkedListSize;
    }

    /**
     * 根据输入的id,查找雇员
     *
     * @param employeeId employee编号
     */
    public void findEmployeeById(int employeeId) {
        // 使用散列函数确定到哪条链表查找
        int EmployeeLinkedListNo = hashFun(employeeId);
        Employee employee = employeeLinkedListArray[EmployeeLinkedListNo].findEmployeeById(employeeId);

        if (Objects.nonNull(employee)) {
            System.out.printf("在第%d条链表中找到 雇员 id = %d\n", (EmployeeLinkedListNo + 1), employeeId);
        } else {
            System.out.println("在哈希表中，没有找到该雇员~");
        }
    }

    /**
     * 遍历所有的链表,遍历hashtable
     */
    public void list() {
        for (int i = 0; i < employeeLinkedListSize; i++) {
            employeeLinkedListArray[i].list(i);
        }
    }
}
